﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using S3.Biz;
using S3.Common;
using S3.DataModel;
using S3.Properties;
using S3.themes;

namespace S3
{
    public partial class MainPaneForm : S3.Common.S3FormBase
    {
        public static string _switchdToDesinationKindOfMachine_From = "";
        public static bool _switchAndStopCurrentPlaying_From;
        public static string _switchdToDesinationKindOfMachine_To = "";
        public static bool _switchAndStopCurrentPlaying_To;
        private Point _activeButtonPosition = Point.Empty;
        private string _oldDeskName = "";
        private string _oldKindOfMachine = "";
        private DateTime _startTime;
        private bool _isShowDefaultDesk;
        private const string MsgRawFinishPlaying = "Chốt tiền giờ chơi {0}?";
        private const string MsgRawQuestionChangeDesk = "Bạn muốn chuyển từ {0} sang {1}?";

        public MainPaneForm(MainForm mainForm)
        {
            this.Main = mainForm;
            ShowLoadingProcess();                        
        }
        public LoginForm LoginFrm { get; set; }


        public void ShowData()
        {
            LoadServices();
            _isShowDefaultDesk = true;
            ShowDeskList(_isShowDefaultDesk);            
        }

        //Load danh sach dich vu
        private void LoadServices()
        {            
            var manager = new GoodsStoreManager();
            comboServices.Properties.Items.Add("+ Chọn dịch vụ +");
            var items = manager.GetAllAvaiable().Select(o => o.ItemName).ToList();
            string[] arrs = new string[items.Count];
            items.CopyTo(arrs);
            comboServices.Properties.Items.AddRange(arrs);
            comboServices.SelectedIndex = 0;
        }


        /// <summary>
        /// Hien thi danh sach ban game
        /// </summary>

        /// <summary>
        /// Display Desk Information
        /// </summary>
        /// <param name="strDeskName"></param>

        /// <summary>
        /// Kich hoat su kien click chon 1 may bat ki
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void ButtonKeyPress(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Enter || e.KeyCode == Keys.Space) && lblStartTime.Text != string.Empty)
            {
                //var viewOrderDetails = new ViewOrderDetails(lblDeskName.Text, this) {MdiParent = ParentForm};
                //viewOrderDetails.ShowDialog();
            }
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            string strDeskName = lblDeskName.Text.Trim();

            if (!string.IsNullOrEmpty(strDeskName))
            {
                //Change color to playing & menucontext

                var button = (SimpleButton) flowLayoutPanel1.GetChildAtPoint(_activeButtonPosition);
                

                //Add daily entry to DB
                AddRecordToDailyEntry(strDeskName, button);
            }
        }

        private void btnPayMoney_Click(object sender, EventArgs e)
        {
            //var viewOrderDetails = new ViewOrderDetails(lblDeskName.Text, this);
            //viewOrderDetails.MdiParent = ParentForm;
            //viewOrderDetails.Closed += viewOrderDetails_Closed;
            //viewOrderDetails.ShowDialog();
        }

        private void viewOrderDetails_Closed(object sender, EventArgs e)
        {
            _isShowDefaultDesk = false;
        }

        private void AddRecordToDailyEntry(string strDeskName, DevExpress.XtraEditors.SimpleButton activeButton)
        {
            //Collect info
            string selectedKindOfMachine = comboKindOfMachine.Text;
            var dailyEntry = new DailyTimingEntry
                                 {
                                     Amount = 0,
                                     TimingServiceName = strDeskName,
                                     Type = selectedKindOfMachine,
                                     ModifiedBy = Constants.StaffName,
                                     ModifiedDate = DateTime.Now,
                                     StaffName = Constants.StaffName,
                                     StartTime = DateTime.Now,
                                     Status = DailyEntryStatusValue.Text[DailyEntryStatus.Playing]
                                 };


            //Check kind of machine before add)
            using (var deskConfigurationManager = new TimingServiceConfigurationManager())
            {
                //declare flag
                bool isExistSelectedKindOfMachine = false;

                string[] listKindOfMachine = deskConfigurationManager.GetKindOfMachineByDesk(strDeskName);
                if (listKindOfMachine != null && listKindOfMachine.Count() > 0)
                {
                    if (listKindOfMachine.Any(machine => machine.ToLower() == selectedKindOfMachine.ToLower()))
                    {
                        isExistSelectedKindOfMachine = true;
                    }

                    //If not exist
                    if (!isExistSelectedKindOfMachine)
                    {
                        //If had only one Kind of machine
                        if (listKindOfMachine.Count() == 1)
                        {
                            dailyEntry.Type = listKindOfMachine.First();
                            isExistSelectedKindOfMachine = true;
                        }
                            //had many other kind of machine
                        else
                        {
                            //Show popup to warning and select other
                            XtraMessageBox.Show(strDeskName + " không có " + selectedKindOfMachine +
                                            ". \nHãy chọn loại khác.");
                            comboKindOfMachine.Focus();
                        }
                    }
                }

                if (isExistSelectedKindOfMachine)
                {
                    //Call to Biz and add into DB
                    using (var dailyEntryManager = new DailyTimingEntryManager())
                    {
                        dailyEntryManager.Add(dailyEntry);
                    }

                    ShowDeskList(false);

                    //Display info
                    DisplayDeskInfo(strDeskName);
                }
            }


            //if (activeButton != null)
            //{

            //    //Apply context menu for playing
            //    activeButton.ContextMenu = MainContextMenu(DailyEntryStatusValue.Text[DailyEntryStatus.Playing]);
            //    //change back color
            //    activeButton.BackColor = themes.Classic.Desk_Playing_BackColor;
            //    activeButton.ForeColor = themes.Classic.Desk_Playing_ForeColor;
            //    //Focus
            //    activeButton.Focus();
            //}
            //else
            //{
            //    //ShowDeskList();
            //}

            ////Change Counter
            //decimal decNotStart = decimal.Parse(lblNotStartCount.Text) - 1;
            //lblNotStartCount.Text = decNotStart + "";

            //decimal decPlaying = decimal.Parse(lblPlayingCount.Text) + 1;
            //lblPlayingCount.Text = decPlaying + "";
        }

        public void ContextMenuStart_Click(object sender, EventArgs e)
        {
            var item = (MenuItem) sender;
            Menu menu = item.Parent;
            ContextMenu a = menu.GetContextMenu();
            string strDeskName = a.SourceControl.Text;

            var button = (DevExpress.XtraEditors.SimpleButton)a.SourceControl;

            AddRecordToDailyEntry(strDeskName, button);
        }

        public void ContextMenuSwitch_Click(object sender, EventArgs e)
        {
            //XtraMessageBox.Show("Hello 1");
        }

        public void ContextMenuEnd_Click(object sender, EventArgs e)
        {
            var a = (MenuItem) sender;
            ContextMenu b = a.Parent.GetContextMenu();
            var button = (DevExpress.XtraEditors.SimpleButton)b.SourceControl;

           // var viewOrderDetails = new ViewOrderDetails(button.Text, this);
            //viewOrderDetails.ShowDialog();
        }

        #region MainContextMenu

        public ContextMenu MainContextMenu(string deskStatus)
        {
            var menu = new ContextMenu();
            //Bat dau
            var item = new MenuItem(MainContextMenuValue.Text[MainFormContextMenu.Start]);
            menu.MenuItems.Add(item);
            menu.MenuItems[0].Click += ContextMenuStart_Click;


            //Chuyen ban
            //item = new MenuItem(MainContextMenuValue.Text[MainFormContextMenu.Switch]);
            //menu.MenuItems.Add(item);
            //menu.MenuItems[1].Click += new EventHandler(ContextMenuSwitch_Click);

            //Nghi choi
            item = new MenuItem(MainContextMenuValue.Text[MainFormContextMenu.End]);
            menu.MenuItems.Add(item);
            menu.MenuItems[1].Click += ContextMenuEnd_Click;

            if (deskStatus.ToLower() == DailyEntryStatusValue.Text[DailyEntryStatus.Playing].ToLower())
            {
                menu.MenuItems[0].Enabled = false;
                menu.MenuItems[1].Enabled = true;
                //menu.MenuItems[2].Enabled = true;
            }
            else
            {
                menu.MenuItems[0].Enabled = true;
                menu.MenuItems[1].Enabled = false;
                //menu.MenuItems[2].Enabled = false;
            }

            return menu;
        }

        #endregion

        #region LoadAdditionalItems

        private void LoadAdditionalItems(string deskName)
        {
            if (string.IsNullOrEmpty(deskName)) deskName = "";


            using (var additionalItemUnitPriceManager = new GoodsStoreManager())
            {
                var itemsList = additionalItemUnitPriceManager.GetAllAvaiable().Select(a => new {a.ItemName});

                using (var dailyAdditionalItemEntryManager = new DailyItemEntryManager())
                {
                    var entries =
                        dailyAdditionalItemEntryManager.GetUnpaidByDesk(deskName).Select(
                            a => new {a.ItemName, a.Quantity});
                    var servicesList = new List<AdditionalServiceQuickView>();

                    foreach (var item in itemsList)
                    {
                        var service = new AdditionalServiceQuickView
                                          {ItemName = item.ItemName, Quantity = 0};

                        foreach (var entry in entries)
                        {
                            if (entry.ItemName.ToLower() == item.ItemName.ToLower())
                            {
                                service.Quantity = entry.Quantity;
                            }
                        }

                        servicesList.Add(service);
                    }

                    gridAdditionalItems.DataSource = servicesList.OrderBy(a => a.ItemName).ToList();
                }
            }
        }

        #endregion

        #region gridAdditionalItems events

        private void gridAdditionalItems_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            object name = e.Row.Cells[0].Value;
            object qty = e.Row.Cells[1].Value;
        }

        private void gridAdditionalItems_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
           // Control control = gridAdditionalItems.Rows[e.RowIndex].Cells[0].DataGridView.Controls[0];
        }

        private void gridAdditionalItems_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
           
        }


        private void btnChangeKindOfMachine_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(lblStartTime.Text) && !string.IsNullOrEmpty(_oldKindOfMachine) &&
                _oldKindOfMachine.ToUpper() != comboKindOfMachine.Text.ToUpper())
            {
                bool? isFinishLastPlaying = null;


                string msg = string.Format(MsgRawFinishPlaying, _oldKindOfMachine);
                DialogResult dialogResult = XtraMessageBox.Show(msg, "Chú ý", MessageBoxButtons.YesNoCancel);

                if (dialogResult == DialogResult.Yes || dialogResult == DialogResult.No)
                {
                    isFinishLastPlaying = dialogResult == DialogResult.Yes ? true : false;
                }


                if (isFinishLastPlaying != null)
                {
                    try
                    {
                        using (var dailyEntryManager = new DailyTimingEntryManager())
                        {
                            string machine = comboKindOfMachine.SelectedItem + "";
                            dailyEntryManager.ChangeKindOfMachine(lblDeskName.Text, machine, isFinishLastPlaying.Value);
                            txtTotalFund.Text =
                                Utils.StringFormatMoney(dailyEntryManager.CalTotalMoneyByDesk(lblDeskName.Text));
                        }

                        XtraMessageBox.Show("Đã chuyển xong");

                        _oldKindOfMachine = comboKindOfMachine.Text;
                    }
                    catch (Exception)
                    {
                        XtraMessageBox.Show("Không thành công. Lỗi khi chuyển loại máy !");
                    }
                }
                else
                {
                    //Cancel
                    comboKindOfMachine.SelectedItem = _oldKindOfMachine;
                }
            }
        }

        private void btnChangeDesk_Click(object sender, EventArgs e)
        {
            try
            {
                string destinationDesk = comboSwitch.Text;
                if (!string.IsNullOrEmpty(destinationDesk))
                {
                    string currentDesk = lblDeskName.Text;
                    string msg = string.Format(MsgRawQuestionChangeDesk, currentDesk, destinationDesk);

                    DialogResult dialogResult = XtraMessageBox.Show(msg, "Chú ý", MessageBoxButtons.YesNo);
                    if (dialogResult == DialogResult.Yes)
                    {
                        //Kiem tra so luong loai may cua may dich:
                        //Neu so luong >1 => hien thi form cho nguoi dung chon loai may muon chuyen sang, neu KH chon loai may khac loai may hien tai thi hoi co muon chot tien may hien tai ko?
                        //Neu so luong = 1 thi kiem tra xem co giong loai may hien tai ko, neu khac thi hoi KH co muon chot tien may hien tai ko?

                        using (var deskConfigurationManager = new TimingServiceConfigurationManager())
                        {
                            //Load Kind of machine
                            string[] destinationKindOfMachineList =
                                deskConfigurationManager.GetKindOfMachineByDesk(destinationDesk);
                            if (destinationKindOfMachineList != null)
                            {
                                if (destinationKindOfMachineList.Count() > 1 || comboKindOfMachine.Items.Count > 1)
                                {
                                    //Hien thi form cho nguoi dung chon loai may muon chuyen sang
                                    var switchForm = new SwitchToAnotherDesk(lblDeskName.Text, destinationDesk,
                                                                             destinationKindOfMachineList,
                                                                             comboKindOfMachine.SelectedItem);
                                    DialogResult result = switchForm.ShowDialog();
                                    if (result == DialogResult.Cancel)
                                    {
                                        comboSwitch.SelectedIndex = 0;
                                        return;
                                    }
                                }
                                else
                                {
                                    _switchdToDesinationKindOfMachine_From = destinationKindOfMachineList.ToList()[0] +
                                                                             "";
                                    _switchdToDesinationKindOfMachine_To = comboKindOfMachine.Text;

                                    //So sanh loai may dich voi may dang choi hien tai
                                    if (comboKindOfMachine.SelectedItem.Equals(destinationKindOfMachineList.ToList()[0]))
                                        //Neu giong nhau
                                    {
                                        _switchAndStopCurrentPlaying_From = false;
                                    }
                                    else //Khac nhau
                                    {
                                        //Hoi xem co muon chot tien may hien tai ko?
                                        string msg1 = string.Format(MsgRawFinishPlaying, _oldKindOfMachine);
                                        DialogResult dialogResult1 = XtraMessageBox.Show(msg1, "Chú ý",
                                                                                     MessageBoxButtons.YesNo);

                                        _switchAndStopCurrentPlaying_From = dialogResult1 == DialogResult.Yes
                                                                                ? true
                                                                                : false;
                                    }
                                }
                            }
                        }

                        using (var dailyEntryManager = new DailyTimingEntryManager())
                        {
                            string desKindOfMachinePlaying =
                                dailyEntryManager.FindKindOfMachineNearestPlayed(comboSwitch.SelectedText);

                            dailyEntryManager.SwitchDesk(currentDesk, comboKindOfMachine.Text,
                                                         _switchdToDesinationKindOfMachine_From,
                                                         _switchAndStopCurrentPlaying_From, comboSwitch.Text,
                                                         desKindOfMachinePlaying, _switchdToDesinationKindOfMachine_To,
                                                         _switchAndStopCurrentPlaying_To);
                        }
                        //ActionLogger.LogAction(ActionType.ChangeDesk, Constants.StaffName, DateTime.Now, new string[] { currentDesk, 
                        //comboKindOfMachine.Text,destinationDesk,_switchdToDesinationKindOfMachine_From,_switchAndStopCurrentPlaying_From?"Có":"Không"});
                        //Refresh
                        ShowData();
                    }

                    comboSwitch.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Lỗi trong quá trình chuyển: " + ex.Message);
            }
        }

        private void comboKindOfMachine_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (btnChangeKindOfMachine.Visible && _oldKindOfMachine != comboKindOfMachine.SelectedItem.ToString())
            {
                btnChangeKindOfMachine.Visible = true;
            }
        }
     

        private void timer1_Tick(object sender, EventArgs e)
        {
            string strDeskName = lblDeskName.Text;
            string strStartTime = lblStartDate.Text;
            if (!string.IsNullOrEmpty(strDeskName) && !string.IsNullOrEmpty(strStartTime))
            {
                using (var dailyEntryManager = new DailyTimingEntryManager())
                {
                    decimal decTotalFund = dailyEntryManager.CalTotalMoneyByDesk(strDeskName);
                    txtTotalFund.Text = Utils.StringFormatMoney(decTotalFund);
                }

                //Used time
                if (_startTime != null)
                {
                    var ts = new TimeSpan();
                    ts = DateTime.Now.Subtract(_startTime);
                    lblUsedTime.Text = string.Format(Constants.Format_Used_Time, ts.Hours, ts.Minutes);
                }
            }
        }

        private void btnAddService_Click(object sender, EventArgs e)
        {
            try
            {
                if (comboServices.SelectedIndex > 0 && numQtyService.Value > 0)
                {
                    using (var manager = new DailyItemEntryManager())
                    {
                        var entry = new DailyItemEntry
                                        {
                                            ItemName = comboServices.SelectedText,
                                            TimingServiceName = lblDeskName.Text,
                                            Quantity = Convert.ToInt32(numQtyService.Value)
                                        };

                        manager.Add(entry);
                    }
                }

                comboServices.SelectedIndex = 0;
                numQtyService.Value = 0;

                //Reload grid
                LoadAdditionalItems(lblDeskName.Text);

                //Plus service money to daily entry
                using (var dailyEntry = new DailyTimingEntryManager())
                {
                    txtTotalFund.Text = Utils.StringFormatMoney(dailyEntry.CalTotalMoneyByDesk(lblDeskName.Text));
                }
                ;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Lỗi khi thêm dịch vụ: " + ex.Message);
            }
        }

        //object serviceList = null;

        //private void gridAdditionalItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        //{
        //    if(string.IsNullOrEmpty(lblDeskName.Text)) return;

        //    DataGridViewComboBoxColumn comboBoxColumn = (DataGridViewComboBoxColumn) gridAdditionalItems.Columns[0];

        //    if (gridAdditionalItems.CurrentCellAddress.X == comboBoxColumn.DisplayIndex)
        //    {
        //        ComboBox cb = (ComboBox)e.Control;
        //        if (cb != null)
        //        {
        //            GoodsStoreManager additionalItemUnitPriceManager = new GoodsStoreManager();
        //            if (serviceList == null)
        //            {
        //                serviceList = additionalItemUnitPriceManager.GetAll(lblDeskName.Text).Select(a=> new {a.ItemName});
        //            }

        //            cb.DataSource = serviceList;
        //            cb.DisplayMember = "ItemName";
        //        }
        //    }
        //}

        //private void gridAdditionalItems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        //{
        //    DataGridViewComboBoxColumn comboBoxColumn = (DataGridViewComboBoxColumn)gridAdditionalItems.Columns[0];

        //    if (gridAdditionalItems.CurrentCellAddress.X == comboBoxColumn.DisplayIndex)
        //    {                
        //        if (!comboBoxColumn.Items.Contains(e.FormattedValue))
        //        {
        //            comboBoxColumn.Items.Add(e.FormattedValue);            
        //        }
        //    }
        //}   

        #endregion

        #region ShowDeskList

        public void ShowDeskList(bool isShowDefaultDesk)
        {
            flowLayoutPanel1.Controls.Clear();
            IList<DevExpress.XtraEditors.SimpleButton> controls = new List<SimpleButton>();
            using (var deskConfigurationManager = new TimingServiceConfigurationManager())
            {
                List<TimingServiceConfiguration> listDesks = deskConfigurationManager.GetAllAvaiableDesks();

                using (var dailyEntryManager = new DailyTimingEntryManager())
                {
                    List<DailyTimingEntry> dailyEntryPlayingList = dailyEntryManager.GetPlayingDesks().ToList();

                    bool isDisplayedFirstPlaying = false;
                    bool isFirstNotPlayingMachine = false;
                    string defaultDeskName = "";
                    DevExpress.XtraEditors.SimpleButton button = null;

                    for (int i = 0; i < listDesks.Count; i++)
                    {
                        TimingServiceConfiguration desk = listDesks[i];
                        if (!isFirstNotPlayingMachine)
                        {
                            isFirstNotPlayingMachine = true;
                            defaultDeskName = desk.TimingServiceName;
                        }

                        //status flags
                        bool isPlaying = false;

                        //Find all playing desk to change the color
                        for (int j = 0; j < dailyEntryPlayingList.Count; j++)
                        {
                            DailyTimingEntry dailyEntryPlaying = dailyEntryPlayingList[j];
                            if (dailyEntryPlaying.TimingServiceName.ToLower() == desk.TimingServiceName.ToLower())
                            {
                                //Mac dinh o trang thai Stop
                                button = Classic.Buttons.Playing();

                                //Change flag
                                if (!isPlaying)
                                {
                                    isPlaying = true;
                                }

                                //Apply context menu for playing
                                button.ContextMenu =
                                    MainContextMenu(DailyEntryStatusValue.Text[DailyEntryStatus.Playing]);
                                //change back color


                                //Display info of the first playing machine
                                if (!isDisplayedFirstPlaying)
                                {
                                    //change flag
                                    isDisplayedFirstPlaying = true;
                                    //display info
                                    defaultDeskName = dailyEntryPlaying.TimingServiceName;
                                }
                            }
                        }

                        if (!isPlaying)
                        {
                            //Hien thi tuong trung, moi ban la 1 button
                            //Mac dinh o trang thai Stop
                            button = Classic.Buttons.Stop();

                            //Set default context menu
                            button.ContextMenu = MainContextMenu("");
                        }

                        //Them se kien cho button
                        //khong dung enter event vi anh huong den viec hien thu du lieu khi load len.                    
                        //button.Enter += new EventHandler(button_Enter);
                        button.Click += button_Enter;
                        button.KeyDown += ButtonKeyPress;
                        button.Text = desk.TimingServiceName;

                        controls.Add(button);
                        //Add button to layout panel
                    }

                    flowLayoutPanel1.Controls.AddRange(controls.ToArray());

                    //Show Notes info
                    int countPlaying = dailyEntryPlayingList.Count();
                    int countTotalDesk = listDesks.Count;
                    int countNotStart = countTotalDesk - countPlaying;

                    //Not Start
                    btnNoteNotStart.BackgroundImage = Resources.FreeIcon;

                    //lblNoteNotStart.Text = DailyEntryStatusValue.Text[DailyEntryStatus.Finished];
                    lblNotStartCount.Text = countNotStart + "";


                    //Playing
                    btnNotePlaying.BackgroundImage = Resources.PlayingIcon;
                    lblNotePlaying.Text = DailyEntryStatusValue.Text[DailyEntryStatus.Playing];
                    lblPlayingCount.Text = countPlaying + "";

                    if (countPlaying <= 0)
                    {
                        btnAddService.Enabled = false;
                    }

                    //Display details info
                    if (isShowDefaultDesk)
                    {
                        DisplayDeskInfo(defaultDeskName);
                    }
                }
            }

            //flowLayoutPanel1.Refresh();
            flowLayoutPanel1.Show();
        }

        #endregion

        #region DisplayDeskInfo

        private void DisplayDeskInfo(string strDeskName)
        {
            //lblDailyEntryID.Text = "0";
            _oldKindOfMachine = "";
            string strStartTime = "";
            string strDate = "";
            string totalFund = "0";
            string usedTime = "0:0:0";
            bool isAllowUpdateAdditionalItem = false;

            //Set enable buttons
            bool btnStartEnabled = true;
            bool btnSwitchEnabled = false;
            bool btnPayMoneyEnabled = false;
            //bool comboKindOfMachineEnabled = true;


            //Show thong tin
            lblDeskName.Text = strDeskName;

            using (var deskConfigurationManager = new TimingServiceConfigurationManager())
            {
                //Load Kind of machine
                string[] kindOfMachineList = deskConfigurationManager.GetKindOfMachineByDesk(strDeskName);
                comboKindOfMachine.DataSource = kindOfMachineList;

                btnChangeKindOfMachine.Enabled = kindOfMachineList != null && kindOfMachineList.Count() > 1
                                                     ? true
                                                     : false;

                //comboKindOfMachine.DisplayMember = "Type";
                ////set default 
                //if (kindOfMachineList.Count > 0)
                //{
                //    strKindOfMachine = kindOfMachineList[0].Type;
                //}

                //Load cac may thong tin bind vao Combobox
                //Get Playing desk
                IEnumerable<string> deskList =
                    deskConfigurationManager.GetAllAvaiableDesks().Where(
                        a => a.TimingServiceName.ToLower() != strDeskName.ToLower()).Select(a => a.TimingServiceName);
                comboSwitch.Items.Clear();
                comboSwitch.Items.Add("");
                foreach (string item in deskList)
                {
                    comboSwitch.Items.Add(item);
                }
            }

            using (var dailyEntryManager = new DailyTimingEntryManager())
            {
                DailyTimingEntry entry = dailyEntryManager.GetOnePlaying(strDeskName);

                bool comboServicesEnable = false;
                string strKindOfMachine;
                bool btnAddServiceEnable;
                bool numQtyServiceEnable;
                bool btnChangeKindOfMachineEnable;
                if (entry != null)
                {
                    //lblDailyEntryID.Text = entry.DailyTimingEntryID + "";

                    //Start time
                    _startTime = entry.StartTime;
                    strStartTime = string.Format(Constants.Format_Hour_Minute, entry.StartTime);

                    //Start date
                    strDate = string.Format(Constants.Format_Day_Month, entry.StartTime);

                    //Kind Of Machine
                    strKindOfMachine = entry.Type;

                    //Used time
                    var ts = new TimeSpan();
                    ts = DateTime.Now.Subtract(entry.StartTime);
                    usedTime = string.Format(Constants.Format_Used_Time, ts.Hours, ts.Minutes);

                    //Test calculate for only game money
                    //Total Fund
                    decimal decTotalFund = dailyEntryManager.CalTotalMoneyByDesk(strDeskName);
                    totalFund = Utils.StringFormatMoney(decTotalFund);

                    //Change enable buttons
                    btnStartEnabled = false;
                    btnSwitchEnabled = true;
                    btnPayMoneyEnabled = true;
                    comboServicesEnable = true;
                    numQtyServiceEnable = true;
                    btnAddServiceEnable = true;
                    btnChangeKindOfMachineEnable = true;
                    //comboKindOfMachineEnabled = false;

                    //Enable & Load Additional items
                    isAllowUpdateAdditionalItem = true;

                    using (var dailyAdditionalItemEntryManager = new DailyItemEntryManager())
                    {
                        IQueryable<DailyItemEntry> addedEntriesList =
                            dailyAdditionalItemEntryManager.GetUnpaidByDesk(strDeskName);
                    }
                }
                else
                {
                    //chuyen loai may sang kieu may mac dinh hoac kieu may choi gan day nhat
                    strKindOfMachine = dailyEntryManager.FindKindOfMachineNearestPlayed(strDeskName);

                    //

                    comboServicesEnable = false;
                    numQtyServiceEnable = false;
                    btnAddServiceEnable = false;
                    btnChangeKindOfMachineEnable = false;
                }

                lblStartTime.Text = strStartTime;
                lblStartDate.Text = strDate;
                txtTotalFund.Text = totalFund;
                lblUsedTime.Text = usedTime;

                comboKindOfMachine.SelectedItem = strKindOfMachine;

                gridAdditionalItems.Enabled = isAllowUpdateAdditionalItem;

                //Set enable buttons
                btnStart.Enabled = btnStartEnabled;
                comboSwitch.Enabled = btnSwitchEnabled;
                btnChangeDesk.Enabled = btnSwitchEnabled;
                btnPayMoney.Enabled = btnPayMoneyEnabled;
                btnAddService.Enabled = btnAddServiceEnable;
                comboServices.Enabled = comboServicesEnable;
                numQtyService.Enabled = numQtyServiceEnable;
                btnChangeKindOfMachine.Enabled = btnChangeKindOfMachineEnable;
                //comboKindOfMachine.Enabled = comboKindOfMachineEnabled;

                //Get tat ca cac ban ghi voi trang thai "Dang choi" va "Da chuyen" cua ban nay
                //Tinh tien cua ban ghi hien tai co trang thai "Dang choi" cong voi tien cua ban ghi "Da chuyen" (neu co)

                //Hien thi dich vu goi them
                LoadAdditionalItems(strDeskName);

                //Set flag 
                _oldDeskName = strDeskName;
                _oldKindOfMachine = comboKindOfMachine.SelectedItem + "";
            }
        }

        #endregion

        #region DeskButton_Click

        private void button_Enter(object sender, EventArgs e)
        {
            //if (!isShowDefaultDesk)
            //{
            string strDeskName = "";
            var button = (DevExpress.XtraEditors.SimpleButton)sender;
            strDeskName = button.Text;
            _activeButtonPosition = button.Location;

            //Display desk information
            DisplayDeskInfo(strDeskName);
            //}

            _isShowDefaultDesk = false;
        }    

        #endregion

        private PopupProgress _popupProgress;      

        private void MainFormShown(object sender, EventArgs e)
        {          
                        
        }

        public void ShowLoadingProcess()
        {
            _popupProgress = new PopupProgress { FormOwner = this, Action = UserAction.Load};
            _popupProgress.OnInitializeComponentHandler += new InitializeComponentHandler(OnInitializeComponentHandler);
            _popupProgress.ShowDialog();
        }

        void OnInitializeComponentHandler()
        {
            InitializeComponent();
        }

        public override void DoLoadData()
        {
            try
            {

                //Check lisence
                //if (CheckLisence())
                //{               

                //Login login = new Login();
                //login.ShowDialog();
                //if (login.IsLoginned)
                //{

                this.ShowData();
                Main.ConfigSecurity();
                
                //}
                //}
                //else
                //{                    
                //    this.Close();        
                //}
            }
            catch (Exception ex)
            {
                using (var log = new SSDLoggingHandler())
                {
                    log.PresentationException(ex.Message, ex, false);
                }

                XtraMessageBox.Show("Có lỗi trong quá trình khởi động phần mềm: " + ex.Message);
                this.Close();
            }  
        }

        public MainForm Main { get; set; }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            object serviceName = gridView1.GetRowCellValue(e.RowHandle, e.Column);
            object qty = e.Value;

            if (serviceName != null && qty != null)
            {
                //Dua dich vu nay vao bang Additional Item
                using (var dailyAdditionalItemEntryManager = new DailyItemEntryManager())
                {
                    var dailyAdditionalItemEntry = new DailyItemEntry
                    {
                        ItemName = serviceName + "",
                        TimingServiceName = lblDeskName.Text,
                        Quantity = Convert.ToInt32(qty),
                        Status =
                            DailyAddditonalItemEntryStatusValue.Text[
                                AdditonalItemEntryStatus.UnPaid],
                        //DailyTimingEntryID = Convert.ToInt64(lblDailyEntryID.Text)
                    };

                    dailyAdditionalItemEntryManager.Save(dailyAdditionalItemEntry);
                }

                //Plus service money to daily entry
                using (var dailyEntry = new DailyTimingEntryManager())
                {
                    txtTotalFund.Text = Utils.StringFormatMoney(dailyEntry.CalTotalMoneyByDesk(lblDeskName.Text));
                }
                ;
            }
        }

    }
}
